// index.js
const app = getApp();
Page({
  data: {
    loading: true,
    loadingBanner: true,
    loadingNotify: true,
    loadingStatistics: true,
    isRegister: false,
    title: '',
    imageUrl: app.globalData.requestUrl,
    safeTop: app.globalData.safearea.top,

    examTypeShow: false,
    examTypeList: []
  },
  onLoad(options) {
    if (options.invite_user_id) {
      app.globalData.invite_user_id = options.invite_user_id ? options.invite_user_id : '';
    }
    let category = app.globalData.category;
    if (!category) {
      this.goSelect();
      return;
    }
    this.setData({
      curCategory: category
    });
    this.isLoad = true;
    this.loadData();
    this.loadBanner(category.id);
    this.loadNotify(category.id);
    const that = this;
    if (!app.globalData.isLogin) {
      app.callback = res => {
        that.setData({
          isRegister: res
        });
        if (res) {
          that.loadStatistics(category.id);
        } else {
          that.setData({
            statistics: {},
            loadingStatistics: false
          });
        }
      }
    } else {
      if (app.globalData.userinfo) {
        that.setData({
          isRegister: true
        });
        that.loadStatistics(category.id);
      } else {
        that.setData({
          statistics: {},
          loadingStatistics: false
        });
      }
    }
  },
  onShow() {
    if (this.isLoad && this.data.curCategory.id !== app.globalData.category.id) {
      this.setData({
        curCategory: app.globalData.category
      });
      this.loadData();
      this.loadBanner(this.data.curCategory.id);
      this.loadNotify(this.data.curCategory.id);
      const that = this;
      if (!app.globalData.isLogin) {
        app.callback = res => {
          that.setData({
            isRegister: res
          });
          if (res) {
            that.loadStatistics(that.data.curCategory.id);
          } else {
            that.setData({
              statistics: {},
              loadingStatistics: false
            });
          }
        }
      } else {
        if (app.globalData.userinfo) {
          that.setData({
            isRegister: true
          });
          that.loadStatistics(that.data.curCategory.id);
        } else {
          that.setData({
            statistics: {},
            loadingStatistics: false
          });
        }
      }
    }
  },
  goExam(e) {
    // 判断是否已开通会员
    if ('vip' in app.globalData.userinfo) {
      if (JSON.stringify(app.globalData.userinfo.vip) === '{}') {
        wx.showModal({
          title: '开通会员',
          content: '解锁本专业全部题目',
          confirmText: '确认开通',
          cancelText: '取消',
          complete: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/buy/buy'
              });
            }
          }
        })
      } else {
        console.log('已开通vip 可以跳转')
        this.doExam(e);
      }
    } else {
      // 一定要存在vip字段，不存在就再获取一遍
      wx.showLoading();
      app.request('/api/user/info', {question_category_id: this.data.curCategory.id}).then(res => {
        app.globalData.userinfo = res.data.data;
        that.goExam(e); // 重复调用
      }).catch(err => {
        console.error(err);
      })
      return;
    }
  },
  doExam(e) {
    switch(e.currentTarget.dataset.type) {
      case '1':
        app.globalData.exam1Params = {
          random: 1
        };
        app.globalData.exam1Title = '随机练习';
        app.globalData.exam1ViewMode = false;
        app.globalData.exam1ShowAnswer = true;
        app.globalData.exam1ParamsNeedLoad = true;
        wx.navigateTo({
          url: '/pages/exam/exam',
        });
        break;
      case '2':
        wx.navigateTo({
          url: '/pages/exam-type/exam-type',
        });
        break;
      case '3':
        this.goExamType();
        app.globalData.exam1Params = {
          right: 0
        };
        app.globalData.exam1Title = '我的错题';
        app.globalData.exam1ViewMode = false;
        app.globalData.exam1ShowAnswer = true;
        app.globalData.exam1ParamsNeedLoad = true;
        break;
      case '4':
        this.goExamType();
        app.globalData.exam1Params = {
          star: 1
        };
        app.globalData.exam1Title = '收藏题目';
        app.globalData.exam1ViewMode = true;
        app.globalData.exam1ShowAnswer = true;
        app.globalData.exam1ParamsNeedLoad = true;
        break;
      case '5':
        this.goExamType();
        app.globalData.exam1Params = {
          answer: 1
        };
        app.globalData.exam1Title = '未做题目';
        app.globalData.exam1ViewMode = false;
        app.globalData.exam1ShowAnswer = true;
        app.globalData.exam1ParamsNeedLoad = true;
        break;
      case '6':
        this.goExamType();
        app.globalData.exam1Params = {};
        app.globalData.exam1Title = '看题模式';
        app.globalData.exam1ViewMode = true;
        app.globalData.exam1ShowAnswer = true;
        app.globalData.exam1ParamsNeedLoad = true;
        break;
      case '7':
        wx.navigateTo({
          url: '/pages/index/history/history',
        });
        break;
      case '8':
        this.goExamType();
        app.globalData.exam1Params = {};
        app.globalData.exam1Title = '考点练习';
        app.globalData.exam1ViewMode = false;
        app.globalData.exam1ShowAnswer = true;
        app.globalData.exam1ParamsNeedLoad = true;
        break;
    }
  },
  onClose() {
    const {examTypeList} = this.data;
    for (let i = 0;i < examTypeList.length;i++) {
      examTypeList[i].isShow = false;
    }
    this.setData({
      examTypeList:examTypeList,
      examTypeShow: false
    });
  },
  confirmSelection() {
    // 拿出已选中的所有选项
    const examTypeList = this.data.examTypeList;
    const type_id = [];
    if (examTypeList[0].isShow) {
      for (const item of examTypeList) {
        if (item.id != 0) type_id.push(item.id);
      }
    } else {
      for (const item of examTypeList) {
        if (item.isShow) type_id.push(item.id);
      }
    }
    if (type_id.length === 0) {
      wx.showToast({
        title: '请选择题型',
        icon: 'none'
      });
      return;
    };
    app.globalData.exam1Params.type_id = type_id;
    wx.navigateTo({
      url: '/pages/exam/exam',
    });
    this.onClose();
  },
  goExamType() {
    const that = this;
    if (this.data.examTypeList.length > 0) {
      that.setData({
        examTypeShow: true
      });
      return;
    }
    app.request('/api/question/type').then(res => {
      console.log(res);
      res.data.data.unshift({
        id: 0,
        name: '全部'
      });
      that.setData({
        examTypeList: res.data.data,
        examTypeShow: true
      });
    }).catch(err => {
      console.error(err);
    });
  },
  selectOption (e) {
    const index = e.currentTarget.dataset.index;
    const examTypeList = this.data.examTypeList;
    if (index === 0) {
      // 全选或全不选
      let res = !examTypeList[0].isShow;
      for (let i = 0;i < examTypeList.length;i++) {
        examTypeList[i].isShow = res;
      }
      this.setData({examTypeList:examTypeList})
    } else {
      this.setData({
        [`examTypeList[${index}].isShow`]: !examTypeList[index].isShow
      });
      let all = true;
      for (let i = 1;i < examTypeList.length;i++) {
        if (!examTypeList[i].isShow) all = false;
      }
      this.setData({
        [`examTypeList[0].isShow`]: all
      });
    }
  },
  getPhoneNumber (e) {
    wx.showLoading();
    const that = this;
    app.register(e).then(res => {
      console.log('注册结果', res);
      that.loadStatistics(that.data.curCategory.id);
      that.setData({
        isRegister: true
      });
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
      console.error(err);
    })
  },
  loadData() {
    wx.showLoading();
    const that = this;
    app.request('/api/question/layout').then(res => {
      let arr = [
        { name: 'notice', sort: res.data.data.notice },
        { name: 'banner', sort: res.data.data.banner },
        { name: 'icon', sort: res.data.data.icon },
        { name: 'info', sort: res.data.data.info }
      ];
      let data = arr.sort((a, b) => a.sort - b.sort);
      that.setData({
        home: data,
        loading: false
      });
      wx.hideLoading();
    }).catch(err => {
      console.error(err);
      wx.hideLoading();
    })
  },
  loadBanner(category_id) {
    const that = this;
    app.request('/api/question/banner', {category_id: category_id}).then(res => {
      that.setData({
        bannerList: res.data.data,
        loadingBanner: false
      });
    }).catch(err => {
      console.error(err);
    })
  },
  loadNotify(category_id) {
    const that = this;
    app.request('/api/question/notice', {category_id: category_id}).then(res => {
      that.setData({
        notifyInfo: res.data.data[0],
        loadingNotify: false
      });
    }).catch(err => {
      console.error(err);
    })
  },
  loadStatistics(category_id) {
    const that = this;
    app.request('/api/question/statistics', {category_id: category_id}).then(res => {
      if (res.data.code === 1) {
        let rate = res.data.data.user_true > 0 ? (res.data.data.user_true / res.data.data.user_total) : 0;
        res.data.data.rate = parseInt(rate * 100);
        that.setData({
          statistics: res.data.data,
          loadingStatistics: false
        });
      } else {
        that.setData({
          statistics: {},
          loadingStatistics: false
        });
      }
    }).catch(err => {
      console.error(err);
    })
  },
  goSelect() {
    wx.redirectTo({
      url: '/pages/category/category?callback=/pages/index/index',
    });
  },
  goNotify() {
    if (this.data.notifyInfo) {
      wx.navigateTo({
        url: './notify/notify?image=' + this.data.notifyInfo.image + '&content=' + this.data.notifyInfo.title + '&title=公告',
      })
    }
  },
  // 考试通知
  goNotifyList() {
    wx.navigateTo({
      url: './notify-list/notify-list',
    });
  },

})
